package com.bs.controller;

import java.util.*;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.bs.bean.*;
import com.bs.service.*;
import com.bs.utils.*;

/*登录：LoginController*/
@Controller
@RequestMapping("/json")
public class LoginController {

//	注入UserService对象
	@Autowired
	private UserService userService;
//	注入AdminService对象
	@Autowired
	private AdminService adminService;
	@RequestMapping("/login")
	public void login(HttpServletRequest request,HttpServletResponse response) throws Exception {
		try {
			String role = request.getParameter("role");
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			if (username==null||username.equals("")||password==null||password.equals("")) {
				throw new Exception("用户名或密码不能为空");
			}
			Object login=null;
			if (role.equals("user")) {
				login = userService.login(username,password);
			}else if (role.equals("admin")) {
				login = adminService.login(username,password);
			}

			ServletContext attributes = request.getServletContext();
			attributes.setAttribute(role, login);
			attributes.setAttribute("login", login);
			attributes.setAttribute("role", role);
				response.getWriter().write(com.alibaba.fastjson.JSONObject.toJSONString(Result.success().put(role, login)));
				return;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.setAttribute("msg", e.getMessage());
			response.getWriter().write(com.alibaba.fastjson.JSONObject.toJSONString(Result.fail(e.getMessage())));
			return;
		}

	}
	@RequestMapping("/register")
	public void register(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String role = request.getParameter("role");
		request.getRequestDispatcher("/json/"+role+"/insert").forward(request, response);;
	}
	@RequestMapping("/logout")
	public void logout(HttpServletRequest request,HttpServletResponse response) throws Exception {
			ServletContext attributes = request.getServletContext();
		Enumeration<String> enumeration = attributes.getAttributeNames();
		while (enumeration.hasMoreElements()) {
			String key = (String) enumeration.nextElement();
			attributes.removeAttribute(key);
		}
		response.getWriter().write(com.alibaba.fastjson.JSONObject.toJSONString(Result.success()));
	}
}
